import { reactive, toRefs, watch } from 'vue'

interface Options<T> {
  formatResult?: (data: T[]) => any
  onSuccess?: () => void
  immediate?: boolean // 是否立即执行查询，默认为true
}
interface PaginationParams {
  page: number
  size: number
  total: number
}
type Api<T> = (params: PaginationParams) => Promise<Page<T>>

export function usePagination<T>(api: Api<T>, options?: Options<T>) {
  const { formatResult, onSuccess, immediate } = options || { pageSize: 10, immediate: true }

  const state = reactive({
    current: 1, // 当前页
    pageSize: 10, // 每页大小
    total: -1,
    records: [],
    status: 'more', // 可选值more loading noMore 和contentText的三个提示语相对应
    contentText: {
      contentdown: '查看更多',
      contentrefresh: '加载中',
      contentnomore: '没有更多了',
    },
    isLoadMore: false,
    loading: false,
  })

  const updateStatus = () => {
    if (state.records.length === state.total) {
      state.contentText.contentdown = '没有更多了'
      state.status = 'noMore'
    } else {
      state.contentText.contentdown = '查看更多'
      state.status = 'more'
      state.isLoadMore = false
    }
  }

  const fetchData = async () => {
    state.loading = true
    try {
      const res = await api({ page: state.current, size: state.pageSize, total: state.total })
      const records = formatResult ? formatResult(res.records) : res.records
      if (state.current === 1) {
        state.records = records
      } else {
        state.records = state.records.concat(records)
      }
      state.total = res.total
      onSuccess?.()
      updateStatus()
    } finally {
      state.loading = false
    }
  }

  const loadmore = async () => {
    if (state.status === 'more' && !state.isLoadMore) {
      state.isLoadMore = true
      state.current += 1
      state.status = 'loading'
      try {
        await fetchData()
      } catch (error) {
        console.error('Error during data loading:', error)
      }
      return true
    }
  }

  const reload = async () => {
    state.total = -1
    state.current = 1
    await fetchData()
  }

  // 是否立即触发
  if (immediate ?? true) {
    fetchData()
  }

  return {
    ...toRefs(state),
    reload,
    loadmore,
  }
}
